package cn.itcast.usermanage.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.itcast.usermanage.mapper.CommonUserMapper;
import cn.itcast.usermanage.mapper.UserMapper;
import cn.itcast.usermanage.pojo.PageResult;
import cn.itcast.usermanage.pojo.User;
import tk.mybatis.mapper.entity.Example;

@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CommonUserMapper commonUserMapper;

	public PageResult<User> queryUserListBypage(Integer page, Integer rows) {
		//查询总数
		//long total = userMapper.queryTotalCount();
		//查询分页数据
		//List<User> users=userMapper.queryUserListBypage((page-1)*rows,rows);
		//开始分页
		PageHelper.startPage(page,rows,true);
		//查询所有信息
//		List<User> users = userMapper.queryUserList();
		List<User> users = commonUserMapper.selectAll();
		//将集合封装到分页信息对象中
		PageInfo<User> info = new PageInfo<>(users);
		//封装到分页vo对象用于页面展示
		PageResult<User> result = new PageResult<>(info.getTotal(),users);
		return result;
	}

	public void saveUser(User user) {
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		commonUserMapper.insertSelective(user);
	}

	public void deleteUserByIds(Long[] ids) {
		List<Object> list = new ArrayList<>();
		// 把数组变为集合
		// 添加元素
		Collections.addAll(list, ids);
		Example example = new Example(User.class);
		//使用in删除
		example.createCriteria().andIn("id", list);
		commonUserMapper.deleteByExample(example);
	}

	public User queryUserById(Long id) {
		return commonUserMapper.selectByPrimaryKey(id);
	}

	public void updateUser(User user) {
		user.setUpdated(new Date());
		commonUserMapper.updateByPrimaryKeySelective(user);
	}

}
